package org.kl.bpm.operation;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.kl.bf.utils.ApplicationContextHelper;
import org.kl.bf.web.base.BasicController;
import org.kl.bpm.entity.conf.BpmConfForm;
import org.kl.bpm.entity.conf.BpmFormTemplate;
import org.kl.bpm.entity.conf.BpmKvProp;
import org.kl.bpm.entity.conf.BpmKvRecord;
import org.kl.bpm.service.conf.BpmConfFormService;
import org.kl.bpm.service.conf.BpmFormTemplateService;
import org.kl.bpm.service.conf.BpmKvPropService;
import org.kl.bpm.service.conf.BpmKvRecordService;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.mapper.JsonMapper;

/**
 * 记录审批信息
 * @author QJ
 * @date 2015年3月21日
 */
public class SetCommentOperation extends AbstractOperation<String> {
	public static final String FORM_FIELD_NAME_VARIABLE = "${nodeName}";
	public static final String OPERATION_TASK_ID = "taskId";
	public static final int STATUS_RUNNING = 2;
	private JsonMapper jsonMapper = new JsonMapper();
	private Task task;
	private Map<String, Object> processParameters;

	public SetCommentOperation(Task task, Map<String, Object> processParameters) {
		this.task = task;
		this.processParameters = processParameters;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public String execute(CommandContext commandContext) {
		String taskId = getParameter(OPERATION_TASK_ID);
		BpmConfFormService bpmConfFormService = getBpmConfFormService();
		BpmFormTemplateService bpmFormTemplateService = getBpmFormTemplateService();
		BpmKvRecordService bpmKvRecordService = getBpmKvRecordService();
		// 尝试根据表单里字段的类型，进行转换
		Map<String, String> formTypeMap = new HashMap<String, String>();
		// 尝试根据表单里字段的类型，进行转换
		Map<String, String> fieldLabelMap = new HashMap<String, String>();
		// 找到表单配置文件
		BpmConfForm bpmConfForm = bpmConfFormService.findByBpmConfNodeBpmConfBaseProcessDefinitionIdAndBpmConfNodeCode(
				task.getProcessDefinitionId(), task.getTaskDefinitionKey());
		// 找到表单模板
		BpmFormTemplate formTemplate = bpmFormTemplateService.getBpmFormTemplate(bpmConfForm.getValue());
		if (formTemplate != null) {
			String content = formTemplate.getContent();
			content = StringUtils.replace(content, FORM_FIELD_NAME_VARIABLE, task.getTaskDefinitionKey());// 将表单中${nodeName}用节点定义KEY替换
			Map map = jsonMapper.fromJson(content, Map.class);
			if (map != null) {
				List<Map> list = (List<Map>) map.get("fields");
				for (Map item : list) {
					formTypeMap.put((String) item.get("name"), (String) item.get("type"));
					fieldLabelMap.put((String) item.get("name"), (String) item.get("label"));
				}
			}
		}
		String processInstanceId = task.getProcessInstanceId();
		BpmKvRecord record = bpmKvRecordService.findByRef(processInstanceId);// 获取审批信息
		record.setStatus(STATUS_RUNNING);
		Set<BpmKvProp> propSet = new HashSet<BpmKvProp>();
		for (String key : formTypeMap.keySet()) {
			BpmKvProp prop = new BpmKvProp();
			prop.setCreateBy(BasicController.getCurrentUserId());
			prop.setCreateDept(BasicController.getCurrentUserDeptId());
			prop.setCreateTime(new Timestamp(System.currentTimeMillis()));
			prop.setCreateMan(BasicController.getCurrentUserName());
			prop.setCreateDeptName(BasicController.getCurrentUserDeptName());
			prop.setBpmKvRecord(record);
			prop.setCode(key);
			prop.setType(RecordBuilder.user_task_data);
			prop.setTaskId(taskId);
			prop.setFieldLabel(this.getFormType(fieldLabelMap, key));// 获取FieldLabel
			prop.setTaskDefinitionKey(task.getTaskDefinitionKey());
			String value = getParameter(key);
			prop.setValue(value);
			propSet.add(prop);
			processParameters.put(key, value);
		}
		record.setBpmKvProps(propSet);
		bpmKvRecordService.saveBpmKvRecord(record);
		return null;
	}

	public Map<String, Object> getProcessParameters() {
		return processParameters;
	}

	public void setProcessParameters(Map<String, Object> processParameters) {
		this.processParameters = processParameters;
	}

	/**
	 * 工具方法，获取表单的类型.
	 */
	private String getFormType(Map<String, String> formTypeMap, String name) {
		if (formTypeMap.containsKey(name)) {
			return formTypeMap.get(name);
		} else {
			return null;
		}
	}

	public boolean notEmpty(String str) {
		return (str != null) && (!"".equals(str));
	}

	public BpmKvRecordService getBpmKvRecordService() {
		return ApplicationContextHelper.getBean(BpmKvRecordService.class);
	}

	public BpmKvPropService getBpmKvPropService() {
		return ApplicationContextHelper.getBean(BpmKvPropService.class);
	}

	public BpmFormTemplateService getBpmFormTemplateService() {
		return ApplicationContextHelper.getBean(BpmFormTemplateService.class);
	}

	public BpmConfFormService getBpmConfFormService() {
		return ApplicationContextHelper.getBean(BpmConfFormService.class);
	}

}
